package com.xqh.study.netflixexampleorder.encrypt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.TreeMap;

/**
 * Description: AES+RSA签名，加密 验签，解密
 *
 * @author: wubaoguo
 * @email: wustrive2008@gmail.com
 * @date: 2015/8/13 15:12
 */
public class MainTest {
    /**
     * 生成 私钥 公钥
     * @see RSAUtils generateKeyPair
     */
    public static final String clientPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCD+V9pAlV+0o/LYYIgYp15ZYvUlTeIBCWlqJ//FRta5+M7IgL5S8Y9zKZQR0osmK56JshfZttVp9LgFUe81rOeH5JPyDHwBy2KnIkrXayDoUxCGwwkoFrlVIBLli9FMS21lXNZJ411AD8AlPOPFJtfJ6ekGLQnBwzQmz54JvlBALzhv34X53oD5Q6QoxcXWK2AzUBcAfmAxe5o+v2kppsLXpxd/nvS8D89Cdh83oPt88YBDyFahripQ3Gb2EFJgJLGGylZ8lkgweouWfSpdWC48gpIiqq05hXFvNRKLJDu6MYgASacoYHVpmP4lkMd3zzZKbcKwTRmEltjF5UYcWUfAgMBAAECggEAW473ZWfMHqdAQW5Nk+A2thEAGKTJGOEfqTU6gwKGruOvnsey3nd2ektvmsRKrnPioDYlzyIRyvQadYHt+hHOHUZ0AEu4cXjZXI/LDj33wH535GjVXNevF+ku9MGl29AJkS+1DcZF+kUIcIPmEX7PaA2f3VWSLn1So6sAhOUtCa3TpzkUMs4hxNmzOe33s+JCE1eT8DA8b20V74LFz0vGM/0DM/Sh9sqa3K4YDE7w6nwtAUE9n0M53VeajdlDa6wLj7E6mm7jiHJamozzAfV60DVVFa417ODTFwiHxBv+gB3ZS2ht8iwsUv+NS2O4qljeXX8QgEGKk2yZBTSWIWPIAQKBgQDOD3XOXZssYdKYVZ9YQ24AojkF1qyW/Uijc/b7mHwQZAxUdtF4vU7oLejv04l9pAuaQisl8IsI8UbVLqY2X1U4zZbF2TvBx+WzFq08QTfxo0ShrI+C7xyXAGXXEQBF7bBb3Y3as8yvY7B9JDmxMU+4xra0krih5+FivUiNWLq5HwKBgQCj9Waf5rKvK2s5vp6uR91r4RvqWC0hES1Mgfs+xYjQr8Kf0qMIUvWoesK37ATyapo7OKua4fJPm/YaUi57kEsZrCQj1eHlLj/ioWpCywd78kcippqlWpQ24Fh6CpUT92eOfAdrrFNlxsAUF9Y/4GyJFjU+WNRJ7BMGqEnPz3fUAQKBgEuKy2t+UZbxvdzu9t3Kypcc4b7MNrWb4Xda2h7ehg0UQJjufli/PiBMRGs3p94Rt9czjtH332DF42vgEDs6s+mBJVcfDpM6D3GaTKQcXMAPVOfYdTxRILATC0LPDsSUIOVs0cZtyAo8h8U49JWLOGjLIMwORfXFJpGmRuTatImNAoGAEx+gZK4n0T6jNw0AvRssvFR5SRAX02+JdQ8EGwI3PwABF1seIO5sMMaAx6sDuLKuYpHtkhcgiCCMx+0l9suRtuDZJkTgIDcQxIJHPpsnuFE98tCz4O17tBretv1c/gMxVPEqfGiRIaHY7X8KQlEO1757X1ZFDIo4feJLGa39MAECgYEAlk+W7KZmQuhMvXaWa7BOt085ySleHwNFRNt32IXiknKTo0OORRMsdECjRamy4jXquYHakSAVtwX4MD8bvrpcLkXtwirQk/gAV/+heieb3Uwo/zVsLDgunFahefiE4rTujKcwby/NboWA6usaFMGYIQQ/MLqPIZmskj3Norpez20=";

    public static final String clientPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg/lfaQJVftKPy2GCIGKdeWWL1JU3iAQlpaif/xUbWufjOyIC+UvGPcymUEdKLJiueibIX2bbVafS4BVHvNaznh+ST8gx8ActipyJK12sg6FMQhsMJKBa5VSAS5YvRTEttZVzWSeNdQA/AJTzjxSbXyenpBi0JwcM0Js+eCb5QQC84b9+F+d6A+UOkKMXF1itgM1AXAH5gMXuaPr9pKabC16cXf570vA/PQnYfN6D7fPGAQ8hWoa4qUNxm9hBSYCSxhspWfJZIMHqLln0qXVguPIK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1k7ojFEpsvTJ8Nd18waWTz2l+5nAbl/6XQ5e3THbPwbXNw2Bf6vLgJFBdhwLcbb7mm5rpLq8XCZooeg5mULmPHIclp/rTOU70NKWOA7/NYf8CgYBkvaMSNwjI7WUJHc9iozqGIq8NTE7OoPnEPVh+UNt2OSGi9W8EZzCdpf0gRP1mg2ocixx8L2dIeAYO/QUAET0jhq14L1RQ8g25Z0ALPyQutqxmiB/+BanuBjSKQ6lb7gLHAYQvDWrC+/7dN3IkQ+Ls+rRaIUkbNfVW/4x2XgpfLQKBgA293iHRWuPpr8lHBaChoQQiu3c9TpW2tfeHb9pmbxubxcevjPyZbcO1N+4EGa4iAeTdNYABv6a2Xn0jjtbPYfERpMOCc51Mu9XC9hFYro5+sY4iu7Gut1pV5be7DLHAGenfBcy5uGIZbVtfMkkHmfSa9F4TXfQR9xSnMbs3GxONAoGAKuCFsi1XHHN58B6BIrPt2npXvyNtWclVjYx5N8NyG6VAHi9MAhty1s+sB/qCTxg8pzzz6PUfe+2PGlOG9xykygWJl9dySnfQUvOUxpxrhpnJyBt+caK4zNBYAc/aS+6rwYe5vY4zjpRLfwiVC9jbmRTGVR05wJ01C+MoQ3fg5wk=";
    public static final String serverPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1yPuluuohv6Vxp/zuGJvaW527CUnMXUSQFuXNsKB1tNff2wjeUY3YwKyCW4OrnDDznubqmcRFD2YE//RS5hKxBQSTIp8B629w/GFhjUM6jWE+ywhjpjXJ71Jfaqh/iDlCRrXUM8476uns45Z/+rNnyTvE0ONbXRErWviGcgpJp7+4V566jg1vVLBJG+yei2G8tQ03DvQVVoibuBJhIy9sLnORbmG/MjALWGfi6QqVntWGEhByCtl98QSVTIBHCF1BPuKiMRM603WpR98W/e1ooilnwKxYH9kxUpNrBdkn7LLbA2TknUGebK5ioipgTAlrM9Aiiw+7KzecItDf5zVwwIDAQAB";
    public static void main(String[] args) throws Exception {
        TreeMap<String, Object> params = new TreeMap<String, Object>();
        params.put("userid", "152255855");
        params.put("phone", "189656214201111");

        client(params);

        server();
    }


    public static void client(TreeMap<String, Object> params) throws Exception {
        // 生成RSA签名
        String sign = EncryptUtils.handleRSA(params, clientPrivateKey);
        params.put("sign", sign);
        System.out.println("签名: "+sign);

        String info = JSON.toJSONString(params);
        //随机生成AES密钥
        String aesKey = SecureRandomUtil.getRandom(16);
        System.out.println("AES秘钥: "+aesKey);
        //AES加密数据
        String data = AESUtils.encryptToBase64(ConvertUtils.stringToHexString(info), aesKey, EncryptConstants.ALGORITHM_ECB_PKCS5);

        // 使用RSA算法将商户自己随机生成的AESkey加密
        String encryptKey = RSAUtils.encrypt(aesKey, serverPublicKey);
        System.out.println("加密后的AES秘钥: "+encryptKey);
        System.out.println("加密后的AES秘钥长度: "+encryptKey.length());


        String tmp = encryptKey + data;
        System.out.println(tmp.length());

        Req.data = data;
        Req.encryptKey = encryptKey;
        System.out.println("tmp===>"+tmp);
        System.out.println("加密后的请求数据:\n" + new Req().toString());
    }

    public static void server() throws Exception {

        // 验签
        boolean passSign = EncryptUtils.checkDecryptAndSign(Req.data,
                Req.encryptKey, clientPublicKey, serverPrivateKey);

        if (passSign) {
            // 验签通过
            String aesKey = RSAUtils.decrypt(Req.encryptKey,
                    serverPrivateKey);
            String data = ConvertUtils.hexStringToString(AESUtils.decryptFromBase64(Req.data,
                    aesKey, EncryptConstants.ALGORITHM_ECB_PKCS5));

            JSONObject jsonObj = JSONObject.parseObject(data);
            String userid = jsonObj.getString("userid");
            String phone = jsonObj.getString("phone");

            System.out.println("解密后的明文:userid:" + userid + " phone:" + phone);

        } else {
            System.out.println("验签失败");
        }
    }

    static class Req {
        public static String data;
        public static String encryptKey;

        @Override
        public String toString() {
            return "data:" + data + "\nencryptKey:" + encryptKey;
        }
    }
}
